/**
 * Created by wxj on 2017/4/1.
 */
$(function () {
  	var bdbVirNode = {
		/* 初始数据 */
		defData: {
			pageSize: 20
		},

		/* 页面状态 */
		pageState: {
		  	page: 1,
			search: '',
		    nodeId:'',
		    searchType: 'physicalNode',
		    noData: 'def'
		},
		resetPageState: function() {
			this.pageState = {
				page: 1,
				search: '',
				nodeId:'',
				searchType: 'physicalNode',
				noData: 'def'
			};

			this.list();
		},

		/* 添加节点 */
		addEvent: function() {
			var _this = this,
				addVerifyObj;

			addVerifyObj = $('#bdb-nodes-add-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
						error.appendTo(element.parents(".bdb-vc"));
					} else {
						error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.addSubmit(form);
				}
			});

			$('#bdb-add-nodes').off('click').on("click", function() {
			  	bdbMain.mLRManag({mask: true, loading: true});
				$.post('/VirtualNode/physicalNodeInit', function(response) {
					if (response.code == 0) {
						_this.addFormFill(addVerifyObj, response.data);
					} else {
						bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
					}
				});
			});
		},

		/* 提交添加的服务器组 */
		addSubmit: function(form) {
			var _this = this,
				form = $(form),
				selectedRipAry = [],
				selectedRipStr = '';

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			$.each(form.find('#js-selSpanAdd span'), function(index, value){
			  	selectedRipAry.push($(value).attr('data-id'));
			});
			selectedRipStr = selectedRipAry.join(',');

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/VirtualNode/addVirtualNode', {
				physicNodeId: form.find("#businessNode").val(),
				serverIpId: form.find("#serviceIP").val(),
				realIp: selectedRipStr
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '添加成功.'}});
					bdbMain.mLSleep({}, function() {
						_this.resetPageState();
					});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert:{type: 2, msg: response.msg}});
				}

			  	bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

	  	/* 添加表单填充 */
	  	addFormFill: function(verifyObj, data) {
			var _this = this,
				DialogEle = $('#bdb-nodes-add-dialog'),
				nodeHtml = bdbMain.attr.selDefOption,
				serverIpHtml = bdbMain.attr.selDefOption;

			// 切换rip表单
		    DialogEle.find('#bdb-serverGroup-textarea').show();
		    DialogEle.find('.bdb-serverGroup-div').hide();

			// 填充物理节点选择框
			$.each(data, function(index, value) {
				nodeHtml += '<option value="' + value.physical_node_id + '">' + value.physical_node_name + '</option>';
			});

			DialogEle.find('#businessNode').html(nodeHtml);
			DialogEle.find('#serviceIP').html(serverIpHtml);

			// 物理节点点击切换
			_this.physicalNodeChange();

			// 搜索事件
		    DialogEle.find('#bdb-search-multisel-servergroup-add').bdbSearchMultisel({eleName: 'caches[]'});

			// 服务IP点击切换
			_this.serverIpChange($('#bdb-nodes-add-dialog'));

		  	bdbMain.mLSleep({loading: false}, function() {
				$(".bdbBlankEle").bdbDialog({
					ele: '#bdb-nodes-add-dialog',
					formObj: verifyObj,
					form: $('#bdb-nodes-add-form'),
					reset: true
				});
			});

		    DialogEle.find('#bdb-serverGroup-list').css('top', 0);
		},

	    /* 编辑表单填充 */
	  	editFormFill: function(verifyObj, data, dataName) {
			var _this = this,
				DialogEle = $('#bdb-nodes-edit-dialog'),
				serverIpHtml = bdbMain.attr.selDefOption,
				ripHtml = '',
				showRipSelHtml = '',
				nodeHtml = '';

			// 填充物理节点
			nodeHtml = '<option value="' + data.physical_node_id + '" selected>' + dataName + '</option>';
			DialogEle.find('#businessNodeEdit').html(nodeHtml);

			// 填充服务IP
			$.each(data.serverIpList, function(i, v) {
				if (v.ip_id == data.virtualNodeList.server_ip_id) {
					serverIpHtml += '<option value="' + v.ip_id + '" selected>' + v.ip + '</option>';
				} else {
					serverIpHtml += '<option value="' + v.ip_id + '">' + v.ip + '</option>';
				}
			});
			DialogEle.find('#serviceIPEdit').html(serverIpHtml);

			// 填充rip,已选择的rip
			var	ripStr = data.virtualNodeList.real_ip_ids,
				ripAry = [];
		    ripAry = ripStr == '' ? [] : ripStr.split(",");

			$.each(data.realIpList, function (j, k) {
				var flag = _this.hasItems(ripAry, k.ip_id),
					checkedFlag = '';

				if (flag == true ){
					showRipSelHtml += '<span data-id="' + k.ip_id + '">' + k.ip + '</span>';
					checkedFlag = 'checked';
				} else {
					checkedFlag = '';
				}

				ripHtml += '<li class="list-row select-items">\
							<input class="list-row-input bdb-f-l" type="checkbox" name="caches[]"  value="' + k.ip_id + '" data-rule-required="true"  data-msg-required="请选择RIP" ' + checkedFlag + '>\
							<span class="bdb-f-l">' + k.ip + '</span>\
							</li>';

			});
		    ripHtml += '<li class="bdb-hide bdb-search-multisel-null">没有匹配的内容!</li>';
			DialogEle.find('.bdb-search-multisel .list').html(ripHtml);

		    DialogEle.find('#js-selSpanEdit').html(showRipSelHtml);

			// 服务IP点击切换
			_this.serverIpChange(DialogEle, data.virtualNodeList.physical_node_id, data.virtualNodeList.virtual_node_id);

			// 搜索事件
		    DialogEle.find('#bdb-search-multisel-servergroup-edit').bdbSearchMultisel({eleName: 'caches[]'});
		    DialogEle.find('#js-selSpanEdit').show();

		    bdbMain.mLSleep({loading: false}, function() {
			  $(".bdbBlankEle").bdbDialog({
				ele: '#bdb-nodes-edit-dialog',
				formObj: verifyObj,
				form: $('#bdb-nodes-edit-form'),
				reset: true
			  });
			});

		    DialogEle.find('#bdb-serverGroup-listEdit').css('top', 0);
		},
		hasItems: function(ary, item) {
			var hasFlag = false;
			$.each(ary, function(i, v) {
				if (item == v) {
					hasFlag = true;
				}
			});
			return hasFlag;
		},

	  	/* 物理节点选择切换 */
	    physicalNodeChange: function() {
		  	var _this = this,
				DialogEle = $('#bdb-nodes-add-dialog');

		    DialogEle.find('#businessNode').off('change').on('change', function(e) {
			    var serverIpHtml = bdbMain.attr.selDefOption,
			        thisPhyNode = $(this).find('option:selected').val();

				// 切换rip表单
				$('#bdb-serverGroup-textarea').show();
				$('.bdb-serverGroup-div').hide();

				$.post('/VirtualNode/serverIpInit', {
					physicalNodeId: thisPhyNode
				},function(response) {
					// 填充服务IP
					$.each(response.data, function (i, n) {
						serverIpHtml += '<option value="' + n.ip_id + '">' + n.ip + '</option>';
					});
				  	DialogEle.find('#serviceIP').html(serverIpHtml);
				});

				// 切换服务器IP
				_this.serverIpChange(DialogEle, thisPhyNode);
			});
		},

	  	/* 服务IP选择切换 */
	  	serverIpChange: function(ele, phyNode, nodeId) {
			var _this = this;

		    ele.find('[name = "serviceIP"]').off('change').on('change', function(e) {
				var ripHtml = '',
				thisServerId = $(this).find('option:selected').val();

				// 切换rip表单
				ele.find('#bdb-serverGroup-textarea').hide();
			    ele.find('.bdb-serverGroup-div').show();
				// 清空spanList
			    ele.find('.bdb-search-multisel .items').empty();

				//拼接参数,如果有nodeId是编辑，如果没有是添加的
			  	var realParam = {};
			  	if(typeof nodeId != 'undefined') {
					realParam = {
						physicalNodeId: phyNode,
						serverIpId: thisServerId,
						virtualNodeId: nodeId
					}

				} else {
					realParam = {
						physicalNodeId: phyNode,
						serverIpId: thisServerId
					}
				}

				// 填充服务器组
				$.post('/VirtualNode/realIpInit', realParam, function(response) {
					if (response.code == 0) {
						$.each(response.data, function(index, value) {
							ripHtml += '<li class="list-row select-items">\
										<input class="list-row-input bdb-f-l" type="checkbox" name="caches[]" value="' + value.ip_id + '" data-rule-required="true" data-msg-required="请选择RIP"><span class="bdb-f-l">' + value.ip + '</span>\
										</li>';
						});
						ripHtml += '<li class="bdb-hide bdb-search-multisel-null">没有匹配的内容!</li>';
						ele.find('.bdb-search-multisel .list').html(ripHtml);
					}
				});
			});
		},

	  	/* 编辑 */
	    editEvent: function(dataId, dataName) {
			var _this = this,
				modifyVerifyObj;

			modifyVerifyObj = $('#bdb-nodes-edit-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
						error.appendTo(element.parents(".bdb-vc"));
					} else {
						error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.modifySubmit(form);
				}
			});

		  	bdbMain.mLRManag({mask: true, loading: true});
			$.post('/VirtualNode/editVirtualNodeInit', {
				'virtualNodeId': dataId
			}, function(response) {
				if (response.code == 0) {
					_this.editFormFill(modifyVerifyObj, response.data, dataName);
				} else {
					bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}
			 });
		},

		/* 提交编辑 */
		modifySubmit: function(form) {
			var _this = this,
				form = $(form),
				selectedRipAry = [],
				selectedRipStr = '';

			$.each($('#js-selSpanEdit span'), function(index, value){
				selectedRipAry.push($(value).attr('data-id'));
			});
			selectedRipStr = selectedRipAry.join(',');

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/VirtualNode/editVirtualNode', {
				virtualNodeId: _this.pageState.nodeId,
				serverIp: form.find("#serviceIPEdit").val(),
				realIp: selectedRipStr
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '修改成功.'}});
					bdbMain.mLSleep({}, function() {
					  	_this.list({page: _this.pageState.page});
					});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
				}
				bdbMain.ajaxInfo.state = 1; // 释放锁.
			});


		},

	  	/* 删除 */
	  	delEvent: function(dataID) {
			var _this = this;
			bdbMain.confirm({
				textInfo: {
					content: '确定要删除吗？',
					btn: {
						ok: '删除',
						cancel: '取消'
					}
				},
				callback: function(ele, params) {
					_this.delProc(ele, dataID);
				}
			});
		},

		/* 删除请求 */
		delProc: function(ele, dataID) {
			var _this = this;

			// 请求已发出.
			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return ;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0;
			bdbMain.mLRManag({mask: true, loading: true});
			$.post('/VirtualNode/deleteVirtualNode', {
				'virtualNodeId': dataID
			}, function(res) {
				if (res.code == 0) {
					bdbMain.mLRManag({loading: false, alert: {type: 1, msg: '删除成功'}});
					bdbMain.mLSleep({}, function() {
						_this.list({page: bdbMain.pageCheck(_this.pageState.page)});
					});
				} else {
					bdbMain.mLRManag({loading: false, alert: {type: 2, msg: res.msg}});
				}
			    bdbMain.ajaxInfo.state = 1;
				ele.hide();
				bdbMain.closeMask();
			});

		},

		/* 列表item操作button */
		listEvent: function() {
			var _this = this;
			$('.bdb-list').off('click').on('click', '.bdb-option-btn', function(e) {
				var ele = $(e.target),
					dataName = ele.parents('.bdb-list-row').attr('data-name'),
					dataId = ele.parents('.bdb-list-row').attr('data-id');
					_this.pageState.nodeId = dataId;
				if (ele.hasClass('node-set')) {
					_this.editEvent(dataId, dataName);
				} else if(ele.hasClass('node-del')) {
					_this.delEvent(dataId);
				}
			});
		},

	  	/* 虚拟节点列表 */
		list: function(obj) {
			var _this = this,
				obj = obj || {page: 1};

			_this.pageState.page = obj.page;
			bdbMain.mLRManag({mask: true, loading: true});
			$.post('/VirtualNode/virtualNodeList', {
				pageNumber: _this.pageState.page,
				pageSize: _this.defData.pageSize,
				query: _this.pageState.search,
			    searchType: _this.pageState.searchType
			}, function(response) {
				var totalRowCnt = 0;
				if (response.code == 0) {
					bdbMain.mLSleep({mask: false, loading: false});
					var listHtml = _this.listProc(response.data);
					totalRowCnt = response.data.total;
					_this.listNull(totalRowCnt);
					$('.bdb-list').html(listHtml);

					// 分页插件展示
					$('#js-bdb-creatPage').bdbPagination({
						totalRowCnt: totalRowCnt,
						currentPage: _this.pageState.page,
						pageSize: _this.defData.pageSize
					});

					// 鼠标滑过显示所有rip
					$('.js-show-tip').bdbTip({
					  eleTopMargin: 129,
					  eleBottomMargin: 53,
					  space: 0,
					  minWidth: 156,
					  maxWidth: 156,
					  padding: '17px 25px 17px 25px',
					  tpl: '<div class="col-md-12 bdb-text-align-c">{data}</div>'
					});

					$('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));
				} else {
					bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}
			});
		},

	  	/* 列表模板 */
		listProc: function(data) {
			var tpl = '',
				realIpStr;
			$.each(data.list, function(index, value) {
			  	realIpStr = value.real_ip_str;
			  	var realIpSplit = realIpStr.split('/');
			  	realIpStr = JSON.stringify(realIpSplit);
				tpl += '<div class="bdb-list-row" data-name="' + value.physical_node_name + '" data-id="' + value.virtual_node_id + '">\
						<div class="bdb-mx-w-col-1 bdb-ellipsis">' + value.virtual_node_id + '</div>\
						<div class="bdb-mx-w-col-2 bdb-ellipsis">' + value.physical_node_name + '</div>\
						<div class="bdb-mx-w-col-3 bdb-ellipsis">' + value.server_ip_str + '</div>\
						<div class="bdb-mx-w-col-4 bdb-ellipsis"><div class="js-show-tip bdb-ellipsis bdb-text-align-c"  data-title= ' + realIpStr + '>' + value.real_ip_str + '</div></div>\
						<div class="bdb-mx-w-col-5">\
						<div class="bdb-option-btn  bdb-p-r bdb-mgn-t-10">\
						<a class="node-set" href="javascript:void(0)">编辑</a>\
						<div class="v-line-ffa007"></div>\
						<a class="bdb-mgn-l--1 bdb-f-c-c8baac node-del" href="javascript:void(0)">删除</a>\
						</div>\
						</div>\
						</div>';
			    });
			return tpl;
		},

	  	/* 页面没有数据 */
		listNull: function(totalRowCnt) {
			var noResult = $('.bdb-no-result'),
				noSearchRecord = $('.bdb-no-search-record');

			if (totalRowCnt <= 0) {
				if (this.pageState.noData == 'search') { // 查询无结果
					noResult.hide();
					noSearchRecord.show();
				} else { // 暂无记录.
					noResult.show();
					noSearchRecord.hide();
				}
			} else {
				noResult.hide();
				noSearchRecord.hide();
			}
		},

	  	/* 搜索事件 */
	  	searchEvent: function() {
			var _this = this,
				searchInputEle = $('.bdb-search-input'),
				selectitem = $('.selectItem');

			$('.search-left-select').off('mouseenter').on('mouseenter', function() {
				selectitem.css('display','block');
			}).off('mouseleave').on('mouseleave', function() {
				selectitem.css('display','none');
			});

			selectitem.off('click').on('click', 'li', function(e) {
				e.stopPropagation();
				$('.search-left-select').find('em').text($(e.target).text()).attr('data-type', $(e.target).attr('data-type'));
				_this.pageState.searchType = $(e.target).attr('data-type');
				selectitem.css('display', 'none');
			});

			searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
				var _cThis = $(this),
					_btnEle = $(this).parent().find('span');

				if (!_btnEle.hasClass('search-clear')) {
					_cThis.animate({width: '240px'}, 500);
					_btnEle.animate({ left : 240 }, 500, function() {
						_btnEle.removeClass('search-gray').addClass('search-blue');
					});
				}
			});

			searchInputEle.off('click').on('click', 'span', function(e) {
				var left = parseInt($(this).css('left'));
				if ($(this).hasClass('search-blue') && left > 0 ) {
					_this.pageState.search = searchInputEle.find('.search-text').val();
					_this.pageState.noData = 'search';
					$(this).removeClass('search-blue').addClass('search-clear');
					_this.list();
				} else if (left > 0){
					searchInputEle.find('.search-text').val('');
					_this.pageState.noData = 'def';
					_this.pageState.search = '';
					$(this).removeClass('search-clear').addClass('search-blue');
					_this.list();
				}
			});
		},

		/* 加载分页 */
		pageEvent: function() {
			var _this = this;
			$('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
				e.preventDefault();
				var page = parseInt($(e.target).text());
				if(!isNaN(page)) {
					_this.list({page: page});
				}
			});
		},

	  	/* 页面高度resize */
		contentSizeResize: function() {
			$(window).resize(function() {
				$('.bdb-list').bdbScreenH(1);
			});
		},
	  	init: function() {
		  	var _this = this;

		  	_this.list();
		  	_this.addEvent();
		  	_this.listEvent();
		  	_this.searchEvent();
		  	_this.contentSizeResize();

		    $('.bdb-list').bdbScreenH(1);
		}
	};

  	bdbVirNode.init();
});